﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Drawing;
using System.Drawing.Imaging;

using System.Collections;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.IO;

namespace Utility
{
    /// <summary>
    /// 生成缩略图
    /// </summary>
    public class XImage
    {
        public Color tBackground;
        public Color tBorder;
        public Color tShadow;
        public int tQuality;
        public string markPosition;
        /// <summary> 
        /// 图片参数预定义 
        /// </summary> 
        static Hashtable htmimes = new Hashtable();
        internal readonly string AllowExt = ".jpe|.jpeg|.jpg|.png|.tif|.tiff|.bmp|.gif";

        //WM_BOTTOM_RIGHT（右下），WM_TOP_LEFT（左上），WM_TOP_RIGHT（右上），WM_BOTTOM_LEFT（左下），WM_CENTER（中间）
        public const string WM_BOTTOM_RIGHT = "WM_BOTTOM_RIGHT";
        public const string WM_TOP_LEFT = "WM_TOP_LEFT";
        public const string WM_TOP_RIGHT = "WM_TOP_RIGHT";
        public const string WM_BOTTOM_LEFT = "WM_BOTTOM_LEFT";
        public const string WM_CENTER = "WM_CENTER";

        //WM_TEXT（文字），WM_IMAGE（图片）
        public const string WM_TEXT = "WM_TEXT";
        public const string WM_IMAGE = "WM_IMAGE";

        public XImage()
        {
            tBackground = Color.Transparent;
            tBorder = Color.Transparent;
            tShadow = Color.Transparent;
            tQuality = 100;
            markPosition = "左下角";
            #region 图片类型预定义

            htmimes[".jpe"] = "image/jpeg";
            htmimes[".jpeg"] = "image/jpeg";
            htmimes[".jpg"] = "image/jpeg";
            htmimes[".png"] = "image/png";
            htmimes[".tif"] = "image/tiff";
            htmimes[".tiff"] = "image/tiff";
            htmimes[".bmp"] = "image/bmp";
            htmimes[".gif"] = "image/gif";

            #endregion
        }

        #region 下载指定URL图片并保存

        /// <summary> 
        /// 下载指定URL的文件并保存到指定目录 
        /// </summary> 
        /// <param name="strUrl"></param> 
        public void DownloadImage(string strUrl, string file)
        {
            System.Net.WebClient wc = new System.Net.WebClient();
            wc.DownloadFile(strUrl, file);
        }

        #endregion

        /// <summary> 
        /// 按给定名字确定颜色 
        /// </summary> 
        /// <param name="name"></param> 
        /// <returns></returns> 
        public Color ToColor(string name)
        {
            if (name == "白色") return Color.White;
            if (name == "红色") return Color.Red;
            if (name == "蓝色") return Color.Blue;
            if (name == "绿色") return Color.Green;
            if (name == "黑色") return Color.Black;
            if (name == "灰色") return Color.DarkGray;
            if (name == "黄色") return Color.Yellow;
            if (name == "紫色") return Color.Cyan;
            if (name == "无色") return Color.Transparent;
            return Color.Transparent;
        }

        /// <summary> 
        /// 按名字设置各种颜色，可以自行扩充:) 
        /// </summary> 
        /// <param name="name"></param> 
        /// <returns></returns> 
        public int ToQuality(string name)
        {
            return Int32.Parse(name.Replace("%", ""));
        }

        /// <summary> 
        /// 获取图像编码解码器的所有相关信息 
        /// </summary> 
        /// <param name="mimeType">包含编码解码器的多用途网际邮件扩充协议 (MIME) 类型的字符串</param> 
        /// <returns>返回图像编码解码器的所有相关信息</returns> 
        private static ImageCodecInfo GetCodecInfo(string mimeType)
        {
            ImageCodecInfo[] CodecInfo = ImageCodecInfo.GetImageEncoders();
            foreach (ImageCodecInfo ici in CodecInfo)
            {
                if (ici.MimeType == mimeType) return ici;
            }
            return null;
        }

        /// <summary> 
        /// 检测扩展名的有效性 
        /// </summary> 
        /// <param name="sExt">文件名扩展名</param> 
        /// <returns>如果扩展名有效,返回true,否则返回false.</returns> 
        private bool CheckValidExt(string sExt)
        {
            bool flag = false;
            string[] aExt = AllowExt.Split('|');
            foreach (string filetype in aExt)
            {
                if (filetype.ToLower() == sExt)
                {
                    flag = true;
                    break;
                }
            }
            return flag;
        }

        private bool _ShowWatermark = true;
        /// <summary>
        /// 是否添加水印
        /// </summary>
        public bool ShowWatermark
        {
            set
            {
                _ShowWatermark = value;
            }
            get
            {
                try
                {
                    return (bool)_ShowWatermark;
                }
                catch
                {
                    return true;
                }
            }
        }

        private bool _GreateSmallImage = true;
        /// <summary>
        /// 是否生成缩略图
        /// </summary>
        public bool GreateSmallImage
        {
            set
            {
                _GreateSmallImage = value;
            }
            get
            {
                try
                {
                    return (bool)_GreateSmallImage;
                }
                catch
                {
                    return true;
                }
            }
        }

        private string _WatermarkType = "WM_TEXT";
        /// <summary>
        /// 水印类型 WM_TEXT（文字），WM_IMAGE（图片）
        /// </summary>
        public string WatermarkType
        {
            set
            {
                _WatermarkType = value;
            }
            get
            {
                return _WatermarkType;
            }
        }

        private string _WatermarkPosition = "WM_BOTTOM_RIGHT";
        /// <summary>
        /// 水印位置 默认 WM_BOTTOM_RIGHT（右下），WM_TOP_LEFT（左上），WM_TOP_RIGHT（右上），WM_BOTTOM_LEFT（左下），WM_CENTER（中间）
        /// </summary>
        public string WatermarkPosition
        {
            set
            {
                _WatermarkPosition = value;
            }
            get
            {
                return _WatermarkPosition;
            }
        }

        private string _WatermarkText = "WWW.SHOVESOFT.COM";
        /// <summary>
        /// 水印字符串
        /// </summary>
        public string WatermarkText
        {
            set
            {
                _WatermarkText = value;
            }
            get
            {
                return _WatermarkText;
            }
        }

        private string _Watermarkimgpath = ""; //水印图片地址，填写虚拟路径
        /// <summary>
        /// 水印图片地址，填写虚拟路径
        /// </summary>
        public string Watermarkimgpath
        {
            set
            {
                _Watermarkimgpath = value;
            }
            get
            {
                return _Watermarkimgpath;
            }
        }

        private int _SmallImage_Width = 100;
        /// <summary>
        /// 缩略图宽度
        /// </summary>
        public int SmallImage_Width
        {
            set
            {
                _SmallImage_Width = value;
            }
            get
            {
                try
                {
                    return ((_SmallImage_Width == 0) ? 100 : (int)_SmallImage_Width);
                }
                catch
                {
                    return 100;
                }
            }
        }

        private int _SmallImage_Height = 75;
        /// <summary>
        /// 缩略图高度
        /// </summary>
        public int SmallImage_Height
        {
            set
            {
                _SmallImage_Height = value;
            }
            get
            {
                try
                {
                    return ((_SmallImage_Height == 0) ? 75 : (int)_SmallImage_Height);
                }
                catch
                {
                    return 75;
                }
            }
        }

        /// <summary>
        /// 上传图片代码
        /// </summary>
        /// <param name="image_file">HtmlInputFile控件</param>
        /// <param name="ImgPath">存放的文件夹绝对位置</param>
        /// <param name="ImgLink">生成的图片的名称带后缀</param>
        /// <returns></returns>        
        public bool UpPic(HttpPostedFile image_file, string ImgPath, string ImgLink, ref string ReturnDescription)
        {
            ReturnDescription = "";

            if (image_file.FileName != null && image_file.FileName.Trim() != "")
            {
                try
                {
                    if (!System.IO.Directory.Exists(ImgPath))
                    {
                        System.IO.Directory.CreateDirectory(ImgPath);
                    }

                    string sExt = ImgLink.Substring(ImgLink.LastIndexOf(".")).ToLower();
                    if (!CheckValidExt(sExt))
                    {
                        ReturnDescription = "原图片文件格式不正确,支持的格式有[ " + AllowExt + " ]";

                        return false;
                    }

                    //是否显示水印
                    if (ShowWatermark)
                    {
                        image_file.SaveAs(ImgPath + "\\" + "old_" + ImgLink);

                        //加水印
                        this.addWaterMark((ImgPath + "\\" + "old_" + ImgLink), (ImgPath + "\\" + ImgLink));
                    }
                    else
                    {
                        image_file.SaveAs(ImgPath + "\\" + ImgLink);
                    }

                    //是否生成缩略图
                    if (GreateSmallImage)
                    {
                        this.GreateMinImage((ImgPath + "\\" + ImgLink), (ImgPath + "\\" + ImgLink.Insert(ImgLink.IndexOf("."), "_Small")), SmallImage_Width, SmallImage_Height);
                    }

                    return true;
                }

                catch
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 添加图片水印
        /// </summary>
        /// <param name="oldpath">原图片绝对地址</param>
        /// <param name="newpath">新图片放置的绝对地址</param>
        private void addWaterMark(string oldpath, string newpath)
        {
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);

                Bitmap b = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb);
                Graphics g = Graphics.FromImage(b);
                g.Clear(Color.White);
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.InterpolationMode = InterpolationMode.High;

                g.DrawImage(image, 0, 0, image.Width, image.Height);

                if (ShowWatermark)
                {
                    switch (WatermarkType)
                    {
                        //是图片的话               
                        case "WM_IMAGE":
                            this.addWatermarkImage(g, HttpContext.Current.Server.MapPath(Watermarkimgpath), WatermarkPosition, image.Width, image.Height);
                            break;
                        //如果是文字                    
                        case "WM_TEXT":
                            this.addWatermarkText(g, WatermarkText, WatermarkPosition, image.Width, image.Height);
                            break;
                    }

                    b.Save(newpath);
                    b.Dispose();
                    image.Dispose();
                }
            }
            catch
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
            finally
            {
                if (File.Exists(oldpath))
                {
                    File.Delete(oldpath);
                }
            }
        }

        /// <summary>
        ///  加水印文字
        /// </summary>
        /// <param name="picture">imge 对象</param>
        /// <param name="_watermarkText">水印文字内容</param>
        /// <param name="_watermarkPosition">水印位置</param>
        /// <param name="_width">被加水印图片的宽</param>
        /// <param name="_height">被加水印图片的高</param>
        private void addWatermarkText(Graphics picture, string _watermarkText, string _watermarkPosition, int _width, int _height)
        {
            int[] sizes = new int[] { 16, 14, 12, 10, 8, 6, 4 };
            Font crFont = null;
            SizeF crSize = new SizeF();
            for (int i = 0; i < 7; i++)
            {
                crFont = new Font("arial", sizes[i], FontStyle.Bold);
                crSize = picture.MeasureString(_watermarkText, crFont);

                if ((ushort)crSize.Width < (ushort)_width)
                {
                    break;
                }
            }

            float xpos = 0;
            float ypos = 0;

            switch (_watermarkPosition)
            {
                case "WM_CENTER":
                    xpos = ((float)_width * (float).01) / 2 - crSize.Width / 2;
                    ypos = ((float)_height * (float).99) / 2 - crSize.Height / 2;
                    break;
                case "WM_TOP_LEFT":
                    xpos = ((float)_width * (float).01) + (crSize.Width / 2);
                    ypos = (float)_height * (float).01;
                    break;
                case "WM_TOP_RIGHT":
                    xpos = ((float)_width * (float).99) - (crSize.Width / 2);
                    ypos = (float)_height * (float).01;
                    break;
                case "WM_BOTTOM_RIGHT":
                    xpos = ((float)_width * (float).99) - (crSize.Width / 2);
                    ypos = ((float)_height * (float).99) - crSize.Height;
                    break;
                case "WM_BOTTOM_LEFT":
                    xpos = ((float)_width * (float).01) + (crSize.Width / 2);
                    ypos = ((float)_height * (float).99) - crSize.Height;
                    break;
            }

            StringFormat StrFormat = new StringFormat();
            StrFormat.Alignment = StringAlignment.Center;

            SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));
            picture.DrawString(_watermarkText, crFont, semiTransBrush2, xpos + 1, ypos + 1, StrFormat);

            SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
            picture.DrawString(_watermarkText, crFont, semiTransBrush, xpos, ypos, StrFormat);

            semiTransBrush2.Dispose();
            semiTransBrush.Dispose();
        }

        //// <summary>
        ///  加水印图片
        /// </summary>
        /// <param name="picture">imge 对象</param>
        /// <param name="WaterMarkPicPath">水印图片的地址</param>
        /// <param name="_watermarkPosition">水印位置</param>
        /// <param name="_width">被加水印图片的宽</param>
        /// <param name="_height">被加水印图片的高</param>
        private void addWatermarkImage(Graphics picture, string WaterMarkPicPath, string _watermarkPosition, int _width, int _height)
        {
            Bitmap watermark = new Bitmap(WaterMarkPicPath);

            ImageAttributes imageAttributes = new ImageAttributes();
            ColorMap colorMap = new ColorMap();

            colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
            colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
            ColorMap[] remapTable = { colorMap };

            imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

            float[][] colorMatrixElements = {
                                              new float[] {1.0f,  0.0f,  0.0f,  0.0f, 0.0f},
                                               new float[] {0.0f,  1.0f,  0.0f,  0.0f, 0.0f},
                                              new float[] {0.0f,  0.0f,  1.0f,  0.0f, 0.0f},
                                              new float[] {0.0f,  0.0f,  0.0f,  0.3f, 0.0f},
                                               new float[] {0.0f,  0.0f,  0.0f,  0.0f, 1.0f}
                                         };

            ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements);

            imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            int xpos = 0;
            int ypos = 0;
            int WatermarkWidth = 0;
            int WatermarkHeight = 0;
            double bl = 1d;
            //计算水印图片的比率
            //取背景的1/4宽度来比较
            if ((_width > watermark.Width * 4) && (_height > watermark.Height * 4))
            {
                bl = 1;
            }
            else if ((_width > watermark.Width * 4) && (_height < watermark.Height * 4))
            {
                bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);

            }
            else

                if ((_width < watermark.Width * 4) && (_height > watermark.Height * 4))
                {
                    bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);
                }
                else
                {
                    if ((_width * watermark.Height) > (_height * watermark.Width))
                    {
                        bl = Convert.ToDouble(_height / 4) / Convert.ToDouble(watermark.Height);

                    }
                    else
                    {
                        bl = Convert.ToDouble(_width / 4) / Convert.ToDouble(watermark.Width);
                    }
                }

            WatermarkWidth = Convert.ToInt32(watermark.Width * bl);
            WatermarkHeight = Convert.ToInt32(watermark.Height * bl);

            switch (_watermarkPosition)
            {
                case "WM_CENTER":
                    xpos = _width / 2 - WatermarkWidth / 2;
                    ypos = _height / 2 - WatermarkHeight / 2;
                    break;
                case "WM_TOP_LEFT":
                    xpos = 10;
                    ypos = 10;
                    break;
                case "WM_TOP_RIGHT":
                    xpos = _width - WatermarkWidth - 10;
                    ypos = 10;
                    break;
                case "WM_BOTTOM_RIGHT":
                    xpos = _width - WatermarkWidth - 10;
                    ypos = _height - WatermarkHeight - 10;
                    break;
                case "WM_BOTTOM_LEFT":
                    xpos = 10;
                    ypos = _height - WatermarkHeight - 10;
                    break;
                default: //右下
                    xpos = _width - WatermarkWidth - 10;
                    ypos = _height - WatermarkHeight - 10;
                    break;
            }

            picture.DrawImage(watermark, new Rectangle(xpos, ypos, WatermarkWidth, WatermarkHeight), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes);

            watermark.Dispose();
            imageAttributes.Dispose();
        }

        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="oldpath">原图片地址</param>
        /// <param name="newpath">新图片地址</param>
        /// <param name="tWidth">缩略图的宽</param>
        /// <param name="tHeight">缩略图的高</param>
        private void GreateMinImage(string oldpath, string newpath, int tWidth, int tHeight)
        {
            try
            {
                System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath);

                double bl = 1d;
                if ((image.Width <= image.Height) && (tWidth >= tHeight))
                {
                    bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
                }
                else if ((image.Width > image.Height) && (tWidth < tHeight))
                {
                    bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
                }
                else

                    if ((image.Width <= image.Height) && (tWidth <= tHeight))
                    {
                        if (image.Height / tHeight >= image.Width / tWidth)
                        {
                            bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
                        }
                        else
                        {
                            bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);
                        }
                    }
                    else
                    {
                        if (image.Height / tHeight >= image.Width / tWidth)
                        {
                            bl = Convert.ToDouble(image.Height) / Convert.ToDouble(tHeight);

                        }
                        else
                        {
                            bl = Convert.ToDouble(image.Width) / Convert.ToDouble(tWidth);
                        }
                    }

                Bitmap b = new Bitmap(image, Convert.ToInt32(image.Width / bl), Convert.ToInt32(image.Height / bl));

                b.Save(newpath);
                b.Dispose();
                image.Dispose();
            }
            catch
            {
            }
        }
    }

}